﻿using CCWin;
using DBToExcel.Code;
using DBToExcel.Model;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DBToExcel
{
    public partial class MainForm : Skin_Metro
    {

        public MainForm()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
        }

        private void LoadData()
        {
            this.BeginInvoke(new Action(() =>
            {
                LoadTempLates(this.TextBox_SqlTemplateName.Text);
            }));
        }

        private void LoadTempLates(string name)
        {
            List<MTemplate> list = ExcelBuilderService.QueryTempLates(name);
            this.DataGridView_SqlTempLate.Rows.Clear();
            this.ComboBox_TempName.Items.Clear();
            if (list != null)
            {
                int index = 0;
                int comidnex = 0;
                foreach (MTemplate item in list)
                {
                    index = this.DataGridView_SqlTempLate.Rows.Add();
                    this.DataGridView_SqlTempLate.Rows[index].Cells["Id"].Value = item.Id;
                    this.DataGridView_SqlTempLate.Rows[index].Cells["TempName"].Value = item.Name;
                    this.DataGridView_SqlTempLate.Rows[index].Cells["IsTempLate"].Value = item.IsTempLate == 1 ? "是" : "否";
                    comidnex = this.ComboBox_TempName.Items.Add(new ComboBoxItem() { Text = item.Name, Value = item.Id });
                }
            }
        }

        private void Button_AddSqlTempLate_Click(object sender, EventArgs e)
        {
            EditTempLate form = new EditTempLate(string.Empty);
            form.ShowDialog(this);
            LoadData();

        }

        private void Button_SeachTemplate_Click(object sender, EventArgs e)
        {
            LoadTempLates(this.TextBox_SqlTemplateName.Text);
        }

        private void DataGridView_SqlTempLate_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.RowIndex == -1)
            {
                return;
            }

            string id = this.DataGridView_SqlTempLate.Rows[e.RowIndex].Cells["Id"].Value.ToString();
            EditTempLate(id);
        }

        private void EditTempLate(string id)
        {
            EditTempLate form = new EditTempLate(id);
            form.ShowDialog(this);
        }


        private void Button_Builde_Click(object sender, EventArgs e)
        {

            ComboBoxItem comitem = this.ComboBox_TempName.SelectedItem as ComboBoxItem;
            if (comitem == null)
            {
                MessageBoxEx.Show("请选择模板", "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            Task.Run(() =>
            {
                try
                {
                    this.por_log.Clear();
                    this.ComboBox_TempName.Enabled = false;
                    this.Button_Builde.Enabled = false;
                    MTempAllInfo mTempAllInfo = ExcelBuilderService.QueryAllInfo(comitem.Value.ToString());
                    BulidExcelUtils utils = new BulidExcelUtils(mTempAllInfo);
                    utils.ProcessingEvent += Utils_ProcessingEvent;
                    MemoryStream ms = utils.Bulid();
                    if (ms == null)
                    {
                        MessageBoxEx.Show("生成Excel失败");
                        return;
                    }

                    this.Invoke(new Action(() =>
                    {
                        ShowSaveFileDialog(ms, comitem.Text + "-" + DateTime.Now.ToString("yyyyMMddHHmmss"));
                    }));
                }
                catch (Exception ex)
                {

                    MessageBoxEx.Show(ex.Message);
                }
                finally
                {
                    this.Button_Builde.Enabled = true;
                    this.ComboBox_TempName.Enabled = true;
                }
            });
        }

        private string ShowSaveFileDialog(MemoryStream ms, string fileName)
        {
            string localFilePath = "";
            //string localFilePath, fileNameExt, newFileName, FilePath; 
            SaveFileDialog sfd = new SaveFileDialog();
            //设置文件类型 
            sfd.Filter = "Excel表格（*.xlsx,）|*.xlsx";
            sfd.Title = "请选择要保存的文件路径";
            sfd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            //设置默认文件类型显示顺序 
            sfd.FilterIndex = 1;

            //保存对话框是否记忆上次打开的目录 
            sfd.RestoreDirectory = true;
            sfd.FileName = fileName + ".xlsx";
            //点了保存按钮进入 
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                localFilePath = sfd.FileName; //获得文件路径 
                using (FileStream fileStream = File.Open(localFilePath, FileMode.OpenOrCreate))
                {
                    byte[] buffer = ms.ToArray();
                    fileStream.Write(buffer, 0, buffer.Length);
                    fileStream.Flush();
                }


                MessageBoxEx.Show("保存成功", "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

            return localFilePath;
        }


        private void Utils_ProcessingEvent(string obj)
        {
            this.Invoke(new Action(() =>
            {
                this.por_log.AppendText(obj + "\r\n");
                this.por_log.ScrollToCaret();
            }));
        }


        private void addconnbtn_Click(object sender, EventArgs e)
        {
            EditDBConn edit = new EditDBConn();
            edit.ShowDialog(this);
            LoadDBConnData();
        }

        private void Tab_Menu_Selected(object sender, TabControlEventArgs e)
        {
            if (e.TabPageIndex == 2)
            {
                LoadDBConnData();
            }

            if (e.TabPageIndex == 1)
            {
                LoadData();
            }
        }

        private void LoadDBConnData()
        {
            List<MDBConn> connns = ExcelBuilderService.QueryAllMDBConns();
            this.dbconngrid.DataSource = connns;
        }

        private void dbconngrid_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1 || e.ColumnIndex == -1)
            {
                return;
            }

            string id = this.dbconngrid.SelectedRows[0].Cells["connId"].Value.ToString();
            EditDBConn edit = new EditDBConn(id);
            edit.ShowDialog(this);
            LoadDBConnData();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            LoadData();
            LoadDBConnData();
            this.Tab_Menu.SelectedIndex = 0;
        }

        private void DataGridView_SqlTempLate_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1 || e.ColumnIndex == -1)
            {
                return;
            }

            string id = this.DataGridView_SqlTempLate.SelectedRows[0].Cells["Id"].Value.ToString();
            EditTempLate edit = new EditTempLate(id);
            edit.ShowDialog(this);
            LoadData();
        }

        private void delBtn_Click(object sender, EventArgs e)
        {
            DataGridViewSelectedRowCollection selRows = this.dbconngrid.SelectedRows;
            if (selRows == null || selRows.Count == 0)
            {
                MessageBoxEx.Show("请选中一条数据");
                return;
            }

            string connId = selRows[0].Cells["connId"].Value.ToString();
            List<MTemplate> list = ExcelBuilderService.QueryTempLates(null);
            if (list != null && list.Count > 0 && list.Count(x => x.ConnId.Equals(connId)) > 0)
            {

                MessageBoxEx.Show("该连接已被模板引用不可删除");
                return;
            }

            if (DialogResult.OK == MessageBoxEx.Show("确认删除此连接数据?", "温馨提示", MessageBoxButtons.OKCancel))
            {
                ExcelBuilderService.DeleteDBConn(connId);
                LoadDBConnData();
            }
        }

        private void deltemplatebtn_Click(object sender, EventArgs e)
        {
            DataGridViewSelectedRowCollection selRows = this.DataGridView_SqlTempLate.SelectedRows;
            if (selRows == null || selRows.Count == 0)
            {
                MessageBoxEx.Show("请选中一条数据");
                return;
            }

            string id = selRows[0].Cells["Id"].Value.ToString();
            if (DialogResult.OK == MessageBoxEx.Show("确认删除此模板数据?", "温馨提示", MessageBoxButtons.OKCancel))
            {
                ExcelBuilderService.DeleteTempLate(id);
                LoadData();
            }
        }

        private void copy_btn_Click(object sender, EventArgs e)
        {
            DataGridViewSelectedRowCollection selRows = this.DataGridView_SqlTempLate.SelectedRows;
            if (selRows == null || selRows.Count == 0)
            {
                MessageBoxEx.Show("请选中一条数据");
                return;
            }

            string id = selRows[0].Cells["Id"].Value.ToString();
            if (DialogResult.OK == MessageBoxEx.Show("确认复制此模板?","温馨提示",MessageBoxButtons.OKCancel))
            {
                MTempAllInfo allInfo = ExcelBuilderService.QueryAllInfo(id);
                allInfo.Template.Name = allInfo.Template.Name + "_copy";
                allInfo.Template.Id = string.Empty;
                allInfo.Map.ForEach(x => x.Id = string.Empty);
                //重新保存一份模板
                FileStream fileStream = File.Open(allInfo.Template.TempPlateExcelFile, FileMode.Open);
                string path = FileConfig.SaveExcelTempLate(fileStream);
                allInfo.Template.TempPlateExcelFile = path;
                if (fileStream != null && fileStream.CanRead)
                {
                    fileStream.Close();
                }
                ExcelBuilderService.Save(allInfo);
                this.LoadTempLates(string.Empty);
            }
        }
    }
}
